<template>
    <div class="employee-profile-page">
        <!-- 頁面標題 -->
        <page-title :title="'員工檔案管理'" />

        <!-- Tab 切換 -->
        <div class="tab-section">
            <el-tabs v-model="activeTab" @tab-click="handleTabChange">
                <el-tab-pane label="教育經歷" name="education"></el-tab-pane>
                <el-tab-pane label="工作經歷" name="work"></el-tab-pane>
                <el-tab-pane label="家庭成員" name="family"></el-tab-pane>
                <el-tab-pane label="員工證書" name="certificate"></el-tab-pane>
            </el-tabs>
        </div>

        <!-- 篩選條件區域 -->
        <div class="filter-section">
            <el-form :model="filterForm" label-width="90px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="職位">
                            <el-select v-model="filterForm.position" placeholder="請選擇職位" clearable>
                                <el-option v-for="item in positionOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="職務">
                            <el-select v-model="filterForm.job" placeholder="請選擇職務" clearable>
                                <el-option v-for="item in jobOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="職級">
                            <el-select v-model="filterForm.rank" placeholder="請選擇職級" clearable>
                                <el-option v-for="item in rankOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="部門">
                            <el-select v-model="filterForm.department" placeholder="請選擇部門" clearable>
                                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="工作地點">
                            <el-select v-model="filterForm.location" placeholder="請選擇工作地點" clearable>
                                <el-option v-for="item in locationOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="選擇日期">
                            <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                                start-placeholder="開始日期" end-placeholder="結束日期" value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="關鍵字搜索">
                            <el-input v-model="filterForm.keyword" :placeholder="searchPlaceholder" clearable
                                @clear="handleSearch" @keyup.enter="handleSearch">
                                <template #append>
                                    <el-button type="primary" @click="handleSearch">
                                        <el-icon>
                                            <Search />
                                        </el-icon>
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按鈕區域 -->
        <div class="action-section">
            <el-button type="primary" @click="addRecord">
                <el-icon>
                    <Plus />
                </el-icon>
                <span>{{ addButtonText }}</span>
            </el-button>
            <el-button type="success" @click="importRecords">
                <el-icon>
                    <Upload />
                </el-icon>
                <span>導入</span>
            </el-button>
            <el-button type="warning" @click="exportRecords">
                <el-icon>
                    <Download />
                </el-icon>
                <span>導出</span>
            </el-button>
            <el-button type="danger" @click="batchDelete" :disabled="selectedRecords.length === 0">
                <el-icon>
                    <Delete />
                </el-icon>
                <span>批量刪除</span>
            </el-button>
        </div>

        <!-- 表格區域 -->
        <div class="table-section">
            <!-- 教育經歷表格 -->
            <el-table v-if="activeTab === 'education'" :data="educationList" style="width: 100%" v-loading="loading"
                class="no-border-table" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="employeeName" label="員工姓名" width="120" />
                <el-table-column prop="employeeId" label="工號" width="120" />
                <el-table-column prop="department" label="部門" width="150" />
                <el-table-column prop="position" label="職位" width="150" />
                <el-table-column prop="education" label="學歷" width="120" />
                <el-table-column prop="school" label="畢業院校" width="180" />
                <el-table-column prop="major" label="專業" width="180" />
                <el-table-column prop="startDate" label="開始時間" width="120" />
                <el-table-column prop="endDate" label="結束時間" width="120" />
                <el-table-column prop="educationType" label="教育類型" width="120" />
                <el-table-column prop="hasDegree" label="是否取得學位" width="120">
                    <template #default="{ row }">
                        <el-tag :type="row.hasDegree ? 'success' : 'info'">
                            {{ row.hasDegree ? '是' : '否' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editRecord(row)">編輯</el-button>
                        <el-button type="danger" size="small" @click="deleteRecord(row.id)">刪除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 工作經歷表格 -->
            <el-table v-else-if="activeTab === 'work'" :data="workList" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="employeeName" label="員工姓名" width="120" />
                <el-table-column prop="employeeId" label="工號" width="120" />
                <el-table-column prop="department" label="部門" width="150" />
                <el-table-column prop="position" label="職位" width="150" />
                <el-table-column prop="company" label="公司名稱" width="180" />
                <el-table-column prop="leavePosition" label="離職時崗位" width="150" />
                <el-table-column prop="entryDate" label="入職日期" width="120" />
                <el-table-column prop="leaveDate" label="離職日期" width="120" />
                <el-table-column prop="duration" label="工作時長" width="120">
                    <template #default="{ row }">
                        {{ row.duration }}年
                    </template>
                </el-table-column>
                <el-table-column prop="leaveSalary" label="離職薪資" width="120">
                    <template #default="{ row }">
                        {{ row.leaveSalary }}元
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editRecord(row)">編輯</el-button>
                        <el-button type="danger" size="small" @click="deleteRecord(row.id)">刪除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 家庭成員表格 -->
            <el-table v-else-if="activeTab === 'family'" :data="familyList" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="employeeName" label="員工姓名" width="120" />
                <el-table-column prop="employeeId" label="工號" width="120" />
                <el-table-column prop="department" label="部門" width="150" />
                <el-table-column prop="position" label="職位" width="150" />
                <el-table-column prop="relationship" label="成員關係" width="120" />
                <el-table-column prop="name" label="成員姓名" width="120" />
                <el-table-column prop="company" label="單位名稱" width="180" />
                <el-table-column prop="memberPosition" label="職位" width="150" />
                <el-table-column prop="birthDate" label="出生日期" width="120" />
                <el-table-column prop="phone" label="手機號碼" width="150" />
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editRecord(row)">編輯</el-button>
                        <el-button type="danger" size="small" @click="deleteRecord(row.id)">刪除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 員工證書表格 -->
            <el-table v-else-if="activeTab === 'certificate'" :data="certificateList" style="width: 100%"
                v-loading="loading" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="employeeName" label="員工姓名" width="120" />
                <el-table-column prop="employeeId" label="工號" width="120" />
                <el-table-column prop="department" label="部門" width="150" />
                <el-table-column prop="position" label="職位" width="150" />
                <el-table-column prop="certificateName" label="證書名稱" width="180" />
                <el-table-column prop="certificateType" label="證書類型" width="150" />
                <el-table-column prop="issuingAuthority" label="發證機構" width="180" />
                <el-table-column prop="certificateNumber" label="證書編號" width="180" />
                <el-table-column prop="issueDate" label="發證日期" width="120" />
                <el-table-column prop="expiryDate" label="有效日期" width="120" />
                <el-table-column label="操作" width="150" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="editRecord(row)">編輯</el-button>
                        <el-button type="danger" size="small" @click="deleteRecord(row.id)">刪除</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分頁 -->
            <div class="pagination-section">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 新增/編輯對話框 -->
        <el-dialog v-model="dialogVisible" :title="`${dialogType === 'add' ? '新增' : '編輯'}${dialogTitle}`" width="600px">
            <div v-if="activeTab === 'education'">
                <!-- 教育經歷表單內容 -->
                <p>教育經歷表單將在這裡顯示</p>
            </div>
            <div v-else-if="activeTab === 'work'">
                <!-- 工作經歷表單內容 -->
                <p>工作經歷表單將在這裡顯示</p>
            </div>
            <div v-else-if="activeTab === 'family'">
                <!-- 家庭成員表單內容 -->
                <p>家庭成員表單將在這裡顯示</p>
            </div>
            <div v-else-if="activeTab === 'certificate'">
                <!-- 員工證書表單內容 -->
                <p>員工證書表單將在這裡顯示</p>
            </div>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitForm">確定</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { Search, Plus, Upload, Download, Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Tab 切換
const activeTab = ref('education')

// 根據 Tab 變化的計算屬性
const searchPlaceholder = computed(() => {
    switch (activeTab.value) {
        case 'education': return '請輸入員工姓名/工號/畢業院校'
        case 'work': return '請輸入員工姓名/工號/公司名稱'
        case 'family': return '請輸入員工姓名/工號/成員姓名'
        case 'certificate': return '請輸入員工姓名/工號/證書名稱'
        default: return '請輸入關鍵字搜索'
    }
})

const addButtonText = computed(() => {
    switch (activeTab.value) {
        case 'education': return '新增教育經歷'
        case 'work': return '新增工作經歷'
        case 'family': return '新增家庭成員'
        case 'certificate': return '新增證書'
        default: return '新增記錄'
    }
})

const dialogTitle = computed(() => {
    switch (activeTab.value) {
        case 'education': return '教育經歷'
        case 'work': return '工作經歷'
        case 'family': return '家庭成員'
        case 'certificate': return '員工證書'
        default: return '記錄'
    }
})

// 篩選表單
const filterForm = reactive({
    position: '',
    job: '',
    rank: '',
    department: '',
    location: '',
    dateRange: [],
    keyword: ''
})

// 下拉選項
const positionOptions = [
    { value: 'manager', label: '經理' },
    { value: 'developer', label: '開發人員' },
    { value: 'designer', label: '設計師' }
]
const jobOptions = [
    { value: 'dev', label: '開發' },
    { value: 'test', label: '測試' },
    { value: 'product', label: '產品' }
]
const rankOptions = [
    { value: 'p1', label: 'P1' },
    { value: 'p2', label: 'P2' },
    { value: 'p3', label: 'P3' }
]
const departmentOptions = [
    { value: 'rd', label: '研發部' },
    { value: 'hr', label: '人事部' },
    { value: 'finance', label: '財務部' }
]
const locationOptions = [
    { value: 'shanghai', label: '上海' },
    { value: 'beijing', label: '北京' },
    { value: 'guangzhou', label: '廣州' }
]

// 表格數據
const loading = ref(false)
const educationList = ref([
    {
        id: 1,
        employeeName: '張三',
        employeeId: '10001',
        department: '研發部',
        position: '前端開發',
        education: '本科',
        school: '清華大學',
        major: '計算機科學與技術',
        startDate: '2015-09-01',
        endDate: '2019-06-30',
        educationType: '全日制',
        hasDegree: true
    }
])
const workList = ref([
    {
        id: 1,
        employeeName: '張三',
        employeeId: '10001',
        department: '研發部',
        position: '前端開發',
        company: '阿里巴巴',
        leavePosition: '高級前端工程師',
        entryDate: '2019-07-15',
        leaveDate: '2021-08-20',
        duration: 2,
        leaveSalary: 25000
    }
])
const familyList = ref([
    {
        id: 1,
        employeeName: '張三',
        employeeId: '10001',
        department: '研發部',
        position: '前端開發',
        relationship: '父親',
        name: '張大',
        company: '某國企',
        memberPosition: '部門經理',
        birthDate: '1970-05-10',
        phone: '13800138000'
    }
])
const certificateList = ref([
    {
        id: 1,
        employeeName: '張三',
        employeeId: '10001',
        department: '研發部',
        position: '前端開發',
        certificateName: 'PMP項目管理專業認證',
        certificateType: '專業認證',
        issuingAuthority: 'PMI',
        certificateNumber: 'PMP123456789',
        issueDate: '2020-05-15',
        expiryDate: '2023-05-15'
    }
])

// 分頁
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 1
})

// 多選
const selectedRecords = ref([])

// 對話框相關
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' or 'edit'
const currentRecord = ref({})

// 方法
const handleTabChange = () => {
    selectedRecords.value = []
    handleSearch()
}

const handleSearch = () => {
    loading.value = true
    // 模擬API請求
    setTimeout(() => {
        loading.value = false
    }, 500)
}

const addRecord = () => {
    dialogType.value = 'add'
    currentRecord.value = {}
    dialogVisible.value = true
}

const editRecord = (record) => {
    dialogType.value = 'edit'
    currentRecord.value = { ...record }
    dialogVisible.value = true
}

const importRecords = () => {
    ElMessage.info('導入功能待實現')
}

const exportRecords = () => {
    ElMessage.info('導出功能待實現')
}

const batchDelete = () => {
    if (selectedRecords.value.length === 0) {
        ElMessage.warning('請至少選擇一條記錄')
        return
    }

    ElMessageBox.confirm(
        `確定要刪除選中的 ${selectedRecords.value.length} 條記錄嗎？`,
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 根據當前Tab刪除對應的數據
        const ids = selectedRecords.value.map(item => item.id)
        switch (activeTab.value) {
            case 'education':
                educationList.value = educationList.value.filter(item => !ids.includes(item.id))
                break
            case 'work':
                workList.value = workList.value.filter(item => !ids.includes(item.id))
                break
            case 'family':
                familyList.value = familyList.value.filter(item => !ids.includes(item.id))
                break
            case 'certificate':
                certificateList.value = certificateList.value.filter(item => !ids.includes(item.id))
                break
        }
        ElMessage.success('刪除成功')
        selectedRecords.value = []
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const deleteRecord = (id) => {
    ElMessageBox.confirm(
        '確定要刪除這條記錄嗎？',
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 根據當前Tab刪除對應的數據
        switch (activeTab.value) {
            case 'education':
                educationList.value = educationList.value.filter(item => item.id !== id)
                break
            case 'work':
                workList.value = workList.value.filter(item => item.id !== id)
                break
            case 'family':
                familyList.value = familyList.value.filter(item => item.id !== id)
                break
            case 'certificate':
                certificateList.value = certificateList.value.filter(item => item.id !== id)
                break
        }
        ElMessage.success('刪除成功')
    }).catch(() => {
        ElMessage.info('已取消刪除')
    })
}

const handleSelectionChange = (selection) => {
    selectedRecords.value = selection
}

const handleSizeChange = (val) => {
    pagination.pageSize = val
    handleSearch()
}

const handleCurrentChange = (val) => {
    pagination.currentPage = val
    handleSearch()
}

const submitForm = () => {
    if (dialogType.value === 'add') {
        // 模擬新增記錄
        const newId = Math.max(
            ...educationList.value.map(r => r.id),
            ...workList.value.map(r => r.id),
            ...familyList.value.map(r => r.id),
            ...certificateList.value.map(r => r.id)
        ) + 1

        const newRecord = {
            id: newId,
            ...currentRecord.value
        }

        switch (activeTab.value) {
            case 'education':
                educationList.value.unshift(newRecord)
                break
            case 'work':
                workList.value.unshift(newRecord)
                break
            case 'family':
                familyList.value.unshift(newRecord)
                break
            case 'certificate':
                certificateList.value.unshift(newRecord)
                break
        }

        ElMessage.success('新增成功')
    } else {
        // 模擬編輯記錄
        let list, index
        switch (activeTab.value) {
            case 'education':
                list = educationList.value
                index = list.findIndex(r => r.id === currentRecord.value.id)
                if (index !== -1) list[index] = currentRecord.value
                break
            case 'work':
                list = workList.value
                index = list.findIndex(r => r.id === currentRecord.value.id)
                if (index !== -1) list[index] = currentRecord.value
                break
            case 'family':
                list = familyList.value
                index = list.findIndex(r => r.id === currentRecord.value.id)
                if (index !== -1) list[index] = currentRecord.value
                break
            case 'certificate':
                list = certificateList.value
                index = list.findIndex(r => r.id === currentRecord.value.id)
                if (index !== -1) list[index] = currentRecord.value
                break
        }

        ElMessage.success('編輯成功')
    }

    dialogVisible.value = false
}
</script>

<style lang="less" scoped>
.employee-profile-page {
    padding: 20px;
    background-color: #fff;

    .tab-section {
        margin-bottom: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 0;
        }
    }

    .filter-section {
        padding: 16px;
        margin-bottom: 16px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    }

    .action-section {
        margin-bottom: 16px;
        display: flex;
        gap: 12px;
    }

    .table-section {
        background-color: #fff;
        padding: 16px;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

        .pagination-section {
            margin-top: 16px;
            display: flex;
            justify-content: flex-end;
        }
    }
}

.no-border-table {

    :deep(.el-table__header),
    :deep(.el-table__body),
    :deep(.el-table__row),
    :deep(.el-table__cell) {
        border: none !important;
    }

    :deep(.el-table__header th) {
        background-color: #f4f8ff;
        font-weight: 600;
        padding: 20px;
    }

    :deep(.el-table__row):hover td {
        background-color: #f5f7fa !important;
    }
}
</style>